<template>
   <v-container class="d-flex justify-center align-center fill-height">
       <v-card
           class="mx-auto pa-10"
           elevation="10"
           min-width="50dvh"
           max-width="60dvh"
       >
         <v-text-field
             v-model="accountInfo.username"
             density="compact"
             prepend-inner-icon="mdi-account"
             variant="outlined"
             :label="$t('text.common.account')"
             :placeholder="$t('placeholder.common.account')"
             clearable
         />
         <v-text-field
             v-model="accountInfo.password"
             type="password"
             density="compact"
             prepend-inner-icon="mdi-lock-outline"
             variant="outlined"
             :label="$t('text.common.password')"
             :placeholder="$t('placeholder.common.password')"
             clearable
         />
         <v-btn
             block
             class="mb-8"
             color="blue"
             size="large"
             variant="tonal"
             @click="loginEvent()"
         >
           {{ $t('button.common.login') }}
         </v-btn>
       </v-card>
   </v-container>
</template>
<script setup lang="ts">
import {useUserStore} from "~/stores/user-store";
import {CLIENT_ERROR_CODE_LIST, ROUTE_MAIN} from "~/resource/constants/common/constant";
import {Token} from "~/resource/types/token/token";
import {useResponseResult} from "~/utils/use-response-result";
import {I18N_PREFIX} from "~~/server/resources/constants/constant";
import {usePostEventFetch} from "~/composables/use-event-fetch";
import {LoginRequest} from "~/resource/types/token/login-request";

const localization = useI18n();
const {clientCode: clientCode, clientSecret: clientSecret} = useRuntimeConfig().public;
const userStore = useUserStore();

const accountInfo = ref<LoginRequest>(new LoginRequest(null, null, 'password', clientSecret, clientCode));
const snackbar = useSnackbar();
const loginEvent = async () => {
  const response = await usePostEventFetch<Token>("/anonymous/oauth/token", {
    params: accountInfo.value
  })
  if (CLIENT_ERROR_CODE_LIST.indexOf(response.code) > -1) {
    snackbar.add(useErrorNotification(localization.t(I18N_PREFIX + response.code)))
  } else if (useResponseResult(response)) {
    userStore.setUser(response.data);
    navigateTo(ROUTE_MAIN);
  } else {
    snackbar.add(useErrorNotification(response.message));
  }
}
</script>